//
// Created by hjie on 23-10-2.
//

#include "message_queue.h"
#include "base_util.h"

PacketMessageQueue::PacketMessageQueue()
{
    m_thread_msg_queue = nullptr;
}

PacketMessageQueue::~PacketMessageQueue()
{
    if (m_thread_msg_queue)
    {
        av_thread_message_queue_free(&m_thread_msg_queue);
        m_thread_msg_queue = nullptr;
        PrintLog("release packet message_queue resource");
    }
}

bool PacketMessageQueue::InitMessageQueue(int size)
{
    av_thread_message_queue_alloc(&m_thread_msg_queue, size, sizeof(AVPacket*));
    return true;
}

int PacketMessageQueue::PushPacket(AVPacket **packet)
{
    return av_thread_message_queue_send(m_thread_msg_queue, packet, 0);
}

int PacketMessageQueue::PopPacketNonBlocking(AVPacket **packet)
{
    return av_thread_message_queue_recv(m_thread_msg_queue, packet, AV_THREAD_MESSAGE_NONBLOCK);
}

int PacketMessageQueue::PopPacket(AVPacket **packet)
{
    return av_thread_message_queue_recv(m_thread_msg_queue, packet, 0);
}

void PacketMessageQueue::SetQueueEof()
{
    av_thread_message_queue_set_err_recv(m_thread_msg_queue, AVERROR_EOF);
}


int PacketMessageQueue::GetSize()
{
    return av_thread_message_queue_nb_elems(m_thread_msg_queue);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


FrameMessageQueue::FrameMessageQueue()
{
    m_thread_msg_queue = nullptr;
}

FrameMessageQueue::~FrameMessageQueue()
{
    if (m_thread_msg_queue)
    {
        av_thread_message_queue_free(&m_thread_msg_queue);
        m_thread_msg_queue = nullptr;
        PrintLog("release frame message_queue resource");
    }
}

bool FrameMessageQueue::InitMessageQueue(int size)
{
    if (m_thread_msg_queue)
    {
        return true;
    }
    av_thread_message_queue_alloc(&m_thread_msg_queue, size, sizeof(AVFrame*));
    return true;
}

int FrameMessageQueue::PushFrame(AVFrame **frame)
{
    return av_thread_message_queue_send(m_thread_msg_queue, frame, 0);
}

int FrameMessageQueue::PopFrameNonBlocking(AVFrame **frame)
{
    return av_thread_message_queue_recv(m_thread_msg_queue, frame, AV_THREAD_MESSAGE_NONBLOCK);
}

int FrameMessageQueue::PopFrame(AVFrame **frame)
{
    return av_thread_message_queue_recv(m_thread_msg_queue, frame, 0);
}

int FrameMessageQueue::GetSize()
{
    return av_thread_message_queue_nb_elems(m_thread_msg_queue);
}

